package com.card.admin.servelt;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.card.mail.GlobMail;
import com.card.mail.MailManager;
import com.card.user.User;
import com.card.user.UserUtils;
import com.xiaoao.net.utils.StringUtil;

public class AddMailServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/plain;charset=utf-8");
		req.setCharacterEncoding("utf-8");
		
		String url="";
		
		String action =req.getParameter("action");
		if(action.equals("add"))
		{
			String addressor = req.getParameter("addressor");
			String mailtitle = req.getParameter("mailtitle");
			String description = req.getParameter("des");
			String rewards = req.getParameter("rewards");
			String starttime = req.getParameter("starttime");
			String endtime = req.getParameter("endtime");
			String receiveId = req.getParameter("receiveId");
			
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date startdate = null;
			Date enddate = null;
			try {
				startdate=sdf.parse(starttime);
				enddate = sdf.parse(endtime);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			GlobMail mail = 
					new GlobMail(addressor, mailtitle, description, rewards, startdate, enddate);
			if(StringUtil.NullOrEmpty(receiveId)) {
				MailManager.getInstance().sendNewMail(mail);
			}else{
				User user = UserUtils.getUserByPrimaryKey(receiveId);
				if(user == null) {
					req.getRequestDispatcher("/info.jsp?info=3").forward(req, res);
					return;
				}
				user.userMail().addPersonalMails(mail);
				user.Store();
			}
		}else if(action.equals("delete")){
			String id = req.getParameter("ID");
			MailManager.getInstance().removeMail(id);
		}
		
		req.getRequestDispatcher("/MailShow.jsp").forward(req, res);
	}
	
}
